import git
import subprocess


def clone_github_repo(repo_url, dest_dir):
    """
    克隆一个 GitHub 仓库到指定的目录，并指定仓库的名字。
    :param repo_url: GitHub 仓库的 URL（如 https://github.com/username/repository.git）
    :param dest_dir: 存放克隆仓库的本地路径
    """
    try:
        # 克隆仓库
        # print(f"Cloning {repo_url} into {dest_dir}...")
        git.Repo.clone_from(repo_url, dest_dir)
        # print(f"Repository successfully cloned into {dest_dir}.")
    except Exception as e:
        print(f"Error occurred while cloning the repository: {str(e)}")


def check_and_pull(repo_url, repo_dir):
    """
    检查本地仓库的远程 URL 是否与给定的 URL 相同，如果不同，则暂停操作。

    :param repo_url: GitHub 仓库的 URL
    :param repo_dir: 本地仓库目录
    """
    try:
        # 打开本地仓库
        repo = git.Repo(repo_dir)

        # 获取当前远程仓库 URL
        current_url = repo.remotes.origin.url

        # print(f"Checking repository {repo_dir}...")

        # 比较给定的仓库 URL 和本地仓库的 URL
        if current_url != repo_url:
            print(f"Warning: The local repository's remote URL does not match the given URL.")
            print(f"Local URL: {current_url}")
            print(f"Given URL: {repo_url}")
            print("Skipping pull operation.")
            return

        # 如果相同，执行 git pull
        # print(f"Pulling from {current_url}...")
        result = repo.remotes.origin.pull()
        # print(f"Successfully pulled from {current_url}.")

    except Exception as e:
        print(f"Error occurred: {str(e)}")

def get_git_remotes(repo_path):
    remotes = subprocess.check_output(['git','remote','-v'],cwd=repo_path).decode('utf-8')
    return remotes

def is_git_remote_change(repo_path,repo_link):
    repo_remote_link = get_git_remotes(repo_path)
    if repo_link in repo_remote_link:
        # print("link right")
        return 0
    else:
        print(repo_link, repo_remote_link)
        return 1
